import moment from "moment"
/**
 * 设置localStorage过期时间
 * @param {*} key 存储的key值
 * @param {*} value  存储的数据
 * @param {*} endtime 到期时间(毫秒)
 */
export const setWithExpiry = (key,value,endtime) => {
    const utc = moment.utc()
    const end = +utc + endtime
    const item = {
        value:{...value},
        end
    }
    localStorage.setItem(key,JSON.stringify(item))
}

/**
 * 验证localStorage是否过期
 * @param {*} key 存储的key值
 */
export const getWithExpiry = (key) => {
    const itemStr = localStorage.getItem(key)
    if(!itemStr){
        return false
    }
    const utc = moment.utc()
    const item = JSON.parse(itemStr);
    if(utc >= item.end){
        ElMessage.error('登录失败,请重新登录')
        localStorage.removeItem(key)
        return false
    }
    return item.value
}